#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import sys
import ConfigParser
import time
import os


def checkSpace(dev):
    import commands
    import re

    space = 10
    line = commands.getoutput("df -B G -P")
    splitline = line.split("\n")
    for item in splitline:
        if item.startswith(dev):
            item = item.rstrip()
            regex = "^.*? *\d*G *\d*G *(\d*)G *\d*% *.*$"
            match = re.match(regex, item)
            if match:
                result = match.group(1)
                space = int(result)
                break
    return space


def countProcess():
    count = 0
    for line in os.popen("ps xa"):
        line = line.rstrip()
        if line.find("Get_PMC_Meta.py") != -1:
            count += 1
    return count

def getFile():
    filename=""
    filelist=os.listdir(".")
    for file in filelist:
        if file[-3:]=="txt":
            filename=file
            break
    return filename



if __name__ == "__main__":
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])
    dev = config.get("node", "dev")

    while True:
        filename=getFile()
        if filename=="":
            break
        else:
            if checkSpace(dev)>=2 and countProcess()==0:
                os.system("python -u Get_PMC_Meta.py "+filename+" &")
        time.sleep(10)